package com.lee.rpc.protocal.spring.service;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.lee.rpc.protocal.annotation.LiServiceProvider;
import com.lee.rpc.protocal.netty.NettyServer;

public class SpringRpcProviderBean implements BeanPostProcessor, InitializingBean{

	private final String serverAddress;
	private final int serverPort;
	
	public SpringRpcProviderBean(String serverAddress, int serverPort) {
		this.serverAddress=  serverAddress;
		this.serverPort = serverPort;
	}
	
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		// TODO Auto-generated method stub
		// 只要是加了LiRemoteReference注解的，都需要发发布到map中，跟spring容器对象隔离
		if(bean.getClass().isAnnotationPresent(LiServiceProvider.class)) {
			Method[] methods = bean.getClass().getDeclaredMethods();
			for(Method method : methods) {
				String serviceName = bean.getClass().getInterfaces()[0].getName();
				String key = serviceName+"."+method.getName();
				System.out.println("key:"+key);
				BeanMethod beanMethod = new BeanMethod();
				beanMethod.setBean(bean);
				beanMethod.setMethod(method);
				Mediator.beanMethodMap.put(key, beanMethod);
			}
		}
		return bean;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		new Thread(()->{
			new NettyServer(serverAddress, serverPort).startNettyServer();; 
		}) .start();
	}

	
	
}
